'use client';

import { useEffect, useState } from 'react';
import { motion } from 'framer-motion';
import { useRouter, useParams } from 'next/navigation';
import { useAuth } from '@/lib/auth-client';
import {
  ArrowLeft,
  BookOpen,
  Lightbulb,
  Target,
  CheckCircle,
  Play,
  Star,
  Clock,
  Users
} from 'lucide-react';
import { DIFFICULTY_LABELS, TOPICS_INDEX } from '@/data/topics-index';

interface Topic {
  id: string;
  name: string;
  description: string;
  category: string;
  gradeLevel: number[];
  difficulty: number;
  examples: string[];
  keyPoints: string[];
  prerequisites?: string[];
}

export default function TopicDetailPage() {
  const [topic, setTopic] = useState<Topic | null>(null);
  const [progress, setProgress] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [currentExample, setCurrentExample] = useState(0);
  const [isLearned, setIsLearned] = useState(false);

  const router = useRouter();
  const params = useParams();
  const { user } = useAuth();

  useEffect(() => {
    if (params.id) {
      loadTopic(params.id as string);
      if (user) {
        loadProgress(params.id as string);
      }
    }
  }, [params.id, user]);

  function loadTopic(topicId: string) {
    try {
      // 从题库索引中查找题型
      const topicData = TOPICS_INDEX.find(t => t.id === topicId);

      if (topicData) {
        setTopic(topicData);
      } else {
        console.error('未找到题型:', topicId);
      }
    } catch (error) {
      console.error('加载知识点详情失败:', error);
    } finally {
      setLoading(false);
    }
  }

  async function loadProgress(topicId: string) {
    try {
      const token = localStorage.getItem('auth_token');
      if (!token) return;

      const response = await fetch(`/api/progress/${topicId}`, {
        headers: {
          'Authorization': `Bearer ${token}`,
        },
        credentials: 'include',
      });

      if (response.ok) {
        const data = await response.json();
        if (data.success && data.data) {
          setProgress(data.data);
          // 设置是否已学会
          setIsLearned(data.data.isLearned || false);
        }
      }
    } catch (error) {
      console.error('加载学习进度失败:', error);
    }
  }

  function startPractice() {
    if (!topic) return;

    // 跳转到练习页面，传递题型ID和默认难度（1-3星，适合算术解法）
    router.push(`/practice/session?topicId=${topic.id}&topicName=${encodeURIComponent(topic.name)}&difficulty=1,2,3&count=10`);
  }

  async function markAsLearned() {
    if (!topic || !user) return;

    try {
      // 调用API标记为已学会
      const response = await fetch('/api/progress/mark-learned', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include',
        body: JSON.stringify({
          topicId: topic.id
        })
      });

      if (response.ok) {
        setIsLearned(true);
        // 重新加载进度
        await loadProgress(topic.id);
      }
    } catch (error) {
      console.error('标记已学会失败:', error);
    }
  }

  function getDifficultyColor(difficulty: number) {
    const colors = {
      1: 'text-green-600 bg-green-100',
      2: 'text-blue-600 bg-blue-100',
      3: 'text-yellow-600 bg-yellow-100',
      4: 'text-orange-600 bg-orange-100',
      5: 'text-red-600 bg-red-100'
    };
    return colors[difficulty as keyof typeof colors] || 'text-gray-600 bg-gray-100';
  }

  function getCategoryIcon(category: string) {
    const icons = {
      '基础计算': '🧮',
      '行程问题': '🚗',
      '几何图形': '📐',
      '数论基础': '🔢',
      '逻辑推理': '🧠',
      '应用问题': '📊',
      '组合计数': '🎲',
      '高级思维': '🎯',
      '代数基础': '📈',
      '函数': '📉',
      '几何基础': '📏',
      '数论进阶': '🔣',
      '组合数学': '🎪',
      '概率统计': '📋'
    };
    return icons[category as keyof typeof icons] || '📚';
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50 flex items-center justify-center">
        <div className="glassmorphism p-8 rounded-2xl">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600 mx-auto"></div>
          <p className="mt-4 text-gray-600">加载知识点详情中...</p>
        </div>
      </div>
    );
  }

  if (!topic) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50 flex items-center justify-center">
        <div className="glassmorphism p-8 rounded-2xl text-center">
          <BookOpen className="w-16 h-16 text-gray-400 mx-auto mb-4" />
          <h3 className="text-xl font-semibold text-gray-600 mb-2">知识点不存在</h3>
          <p className="text-gray-500 mb-4">请检查链接是否正确</p>
          <button
            onClick={() => router.back()}
            className="glassmorphism-button px-6 py-2 rounded-lg"
          >
            返回
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50">
      {/* 导航栏 */}
      <nav className="glassmorphism-nav sticky top-0 z-50 backdrop-blur-md bg-white/10 border-b border-white/20">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center h-16">
            <div className="flex items-center space-x-4">
              <button
                onClick={() => router.push('/learn')}
                className="p-2 rounded-lg hover:bg-white/20 transition-colors"
                title="返回学习中心"
              >
                <ArrowLeft className="w-5 h-5 text-gray-600" />
              </button>
              <div className="flex items-center space-x-2">
                <span className="text-2xl">{getCategoryIcon(topic.category)}</span>
                <h1 className="text-2xl font-bold bg-gradient-to-r from-indigo-600 to-purple-600 bg-clip-text text-transparent">
                  {topic.name}
                </h1>
              </div>
            </div>
            <div className="flex items-center space-x-4">
              {isLearned ? (
                <div className="flex items-center space-x-2 text-green-600">
                  <CheckCircle className="w-5 h-5" />
                  <span className="text-sm font-medium">已学会</span>
                </div>
              ) : (
                <button
                  onClick={markAsLearned}
                  className="glassmorphism-button px-4 py-2 rounded-lg text-sm font-medium"
                >
                  标记为已学会
                </button>
              )}
            </div>
          </div>
        </div>
      </nav>

      <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* 知识点信息 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="glassmorphism p-6 rounded-2xl mb-8"
        >
          <div className="flex flex-wrap items-center gap-4 mb-4">
            <span className={`px-3 py-1 rounded-full text-sm font-medium ${getDifficultyColor(topic.difficulty)}`}>
              {DIFFICULTY_LABELS[topic.difficulty as keyof typeof DIFFICULTY_LABELS]}
            </span>
            <span className="px-3 py-1 bg-indigo-100 text-indigo-700 rounded-full text-sm font-medium">
              {topic.category}
            </span>
            <span className="px-3 py-1 bg-purple-100 text-purple-700 rounded-full text-sm font-medium">
              {topic.gradeLevel.join('-')}年级
            </span>
          </div>
          
          <p className="text-gray-700 text-lg leading-relaxed">
            {topic.description}
          </p>
        </motion.div>

        {/* 核心要点 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.1 }}
          className="glassmorphism p-6 rounded-2xl mb-8"
        >
          <h2 className="text-xl font-semibold text-gray-800 mb-4 flex items-center">
            <Lightbulb className="w-6 h-6 mr-2 text-yellow-500" />
            核心要点
          </h2>
          <div className="space-y-3">
            {topic.keyPoints.map((point, index) => (
              <motion.div
                key={index}
                initial={{ opacity: 0, x: -20 }}
                animate={{ opacity: 1, x: 0 }}
                transition={{ delay: 0.1 * index }}
                className="flex items-start space-x-3"
              >
                <div className="w-6 h-6 bg-indigo-100 text-indigo-600 rounded-full flex items-center justify-center text-sm font-medium mt-0.5">
                  {index + 1}
                </div>
                <p className="text-gray-700 flex-1">{point}</p>
              </motion.div>
            ))}
          </div>
        </motion.div>

        {/* 经典例题 */}
        {topic.examples.length > 0 && (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.2 }}
            className="glassmorphism p-6 rounded-2xl mb-8"
          >
            <h2 className="text-xl font-semibold text-gray-800 mb-4 flex items-center">
              <Target className="w-6 h-6 mr-2 text-green-500" />
              经典例题
            </h2>
            
            {topic.examples.length > 1 && (
              <div className="flex space-x-2 mb-4">
                {topic.examples.map((_, index) => (
                  <button
                    key={index}
                    onClick={() => setCurrentExample(index)}
                    className={`px-3 py-1 rounded-lg text-sm font-medium transition-colors ${
                      currentExample === index
                        ? 'bg-indigo-600 text-white'
                        : 'bg-white/50 text-gray-600 hover:bg-white/70'
                    }`}
                  >
                    例题 {index + 1}
                  </button>
                ))}
              </div>
            )}

            <div className="bg-white/30 p-6 rounded-lg space-y-6">
              {/* 题目部分 */}
              <div className="border-l-4 border-indigo-500 pl-4 bg-white/20 p-4 rounded-r-lg">
                <h3 className="font-semibold text-indigo-700 mb-3 flex items-center">
                  <Target className="w-5 h-5 mr-2" />
                  题目
                </h3>
                <p className="text-gray-800 text-lg leading-relaxed whitespace-pre-line">
                  {topic.examples[currentExample].split('\n\n【解题思路】')[0] ||
                   topic.examples[currentExample].split('\n\n第一步')[0] ||
                   topic.examples[currentExample].split('\n\n')[0]}
                </p>
              </div>

              {/* 解题思路部分 */}
              {topic.examples[currentExample].includes('【解题思路】') && (
                <div className="border-l-4 border-green-500 pl-4 bg-white/20 p-4 rounded-r-lg">
                  <h3 className="font-semibold text-green-700 mb-3 flex items-center">
                    <Lightbulb className="w-5 h-5 mr-2" />
                    解题思路
                  </h3>
                  <div className="text-gray-700 leading-relaxed whitespace-pre-line">
                    {topic.examples[currentExample].split('【解题思路】')[1]?.split('\n\n【')[0] ||
                     topic.examples[currentExample].split('【解题思路】')[1]}
                  </div>
                </div>
              )}
            </div>
          </motion.div>
        )}

        {/* 开始练习 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.3 }}
          className="glassmorphism p-6 rounded-2xl"
        >
          <h2 className="text-xl font-semibold text-gray-800 mb-4">准备好了吗？</h2>
          <p className="text-gray-600 mb-6">
            现在你已经学习了{topic.name}的核心要点，是时候通过练习来巩固知识了！
          </p>
          
          <div className="flex flex-col sm:flex-row gap-4">
            <button
              onClick={startPractice}
              className="flex-1 glassmorphism-button p-4 rounded-xl text-left hover:scale-105 transition-transform"
            >
              <div className="flex items-center justify-between">
                <div className="flex-1">
                  <div className="font-medium text-gray-800 flex items-center">
                    <Play className="w-5 h-5 mr-2 text-indigo-500" />
                    开始练习
                  </div>
                  <div className="text-sm text-gray-600">默认1-3星难度（算术解法）</div>
                  <div className="text-xs text-blue-600 mt-1">💡 需要其他难度？前往"自由练习"</div>
                </div>
              </div>
            </button>
            
            <button
              onClick={() => router.push('/practice/daily')}
              className="flex-1 glassmorphism-button p-4 rounded-xl text-left hover:scale-105 transition-transform"
            >
              <div className="flex items-center justify-between">
                <div>
                  <div className="font-medium text-gray-800 flex items-center">
                    <Star className="w-5 h-5 mr-2 text-yellow-500" />
                    每日练习
                  </div>
                  <div className="text-sm text-gray-600">综合练习巩固</div>
                </div>
              </div>
            </button>
          </div>
        </motion.div>
      </div>
    </div>
  );
}
